package org.huhu.mercury.dal;

import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
 * 数据库命名策略
 * 和hibernate4有区别
 */
@Component("databaseNamingStrategy")
public class DatabaseNamingStrategy extends org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl {

	private static final long serialVersionUID = 4614294361681654588L;
	
	@Value("${namingStrategy.tablePrefix}")
	private String tablePrefix="themis_";// 数据库表名前缀
	private Boolean isAddUnderscores=true;// 是否以下划线形式命名
	private Integer maxLength=60;// 命名最大长度限制

	public static String addUnderscores(String name) {
		if (name == null) {
			return null;
		}
		StringBuffer stringBuffer = new StringBuffer(name.replace('.', '_'));
		for (int i = 1; i < stringBuffer.length() - 1; i++) {
			if (Character.isLowerCase(stringBuffer.charAt(i-1)) && Character.isUpperCase(stringBuffer.charAt(i)) && Character.isLowerCase(stringBuffer.charAt(i+1))) {
				stringBuffer.insert(i++, '_');
			}
		}
		return stringBuffer.toString().toLowerCase();
	}

	@Override
	public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
		return new Identifier(tablePrefix + addUnderscores(name.getText()), name.isQuoted());
	}

	@Override
	public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
		return new Identifier(addUnderscores(name.getText()), name.isQuoted());
	}
	
	public String getTablePrefix() {
		return tablePrefix;
	}

	public void setTablePrefix(String tablePrefix) {
		this.tablePrefix = tablePrefix;
	}

	public Boolean getIsAddUnderscores() {
		return isAddUnderscores;
	}

	public void setIsAddUnderscores(Boolean isAddUnderscores) {
		this.isAddUnderscores = isAddUnderscores;
	}

	public Integer getMaxLength() {
		return maxLength;
	}

	public void setMaxLength(Integer maxLength) {
		this.maxLength = maxLength;
	}

}